package cn.hh.redis.util;

import cn.hutool.core.io.IoUtil;
import org.apache.sshd.client.SshClient;
import org.apache.sshd.client.config.hosts.HostConfigEntry;
import org.apache.sshd.client.session.ClientSession;
import org.apache.sshd.sftp.client.SftpClient;
import org.apache.sshd.sftp.client.SftpClientFactory;
import org.springframework.beans.factory.annotation.Value;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.*;

/**
 * @Author huangh
 * @date 2021/12/01
 * @Description: 连接sftp服务器工具类
 */
public class SFTPUtil {

    @Value("{sftp.username}")
    private String sftpUserName;
    @Value("{sftp.password}")
    private String sftpPassword;
    @Value("{sftp.addr}")
    private String sftpAddr;

    /**
     * 写文件
     * @param localPath
     * @param remotePath
     * @throws IOException
     */
    public static void uploadSFTP(String localPath, String remotePath) throws IOException {
        SshClient client = SshClient.setUpDefaultClient();
        client.start();
        ClientSession session = client.connect("hh", "127.0.0.1", 22).verify().getSession();
        session.addPasswordIdentity("et31415926");
        session.auth().verify();

        SftpClientFactory factory = SftpClientFactory.instance();
        SftpClient sftp = factory.createSftpClient(session);

        SftpClient.CloseableHandle handle = sftp.open(remotePath,
                EnumSet.of(SftpClient.OpenMode.Write, SftpClient.OpenMode.Create));

        FileInputStream in = new FileInputStream(localPath);
        int buff_size = 1024 * 1024;
        byte[] src = new byte[buff_size];
        int len;
        long fileOffset = 0l;
        while ((len = in.read(src)) != -1) {
            sftp.write(handle, fileOffset, src, 0, len);
            fileOffset += len;
        }

        in.close();
        sftp.close(handle);

        session.close(false);
        client.stop();
    }

    /**
     * 读文件
     * @param localPath
     * @param remotePath
     * @throws IOException
     */
    public static void readSFTP(String localPath, String remotePath) throws IOException {
        SshClient client = SshClient.setUpDefaultClient();
        client.start();
        ClientSession session = client.connect("hh", "127.0.0.1", 22).verify().getSession();
        session.addPasswordIdentity("et31415926");
        session.auth().verify();

        SftpClientFactory factory = SftpClientFactory.instance();
        SftpClient sftp = factory.createSftpClient(session);

        SftpClient.CloseableHandle handle = sftp.openDir(remotePath);

        //获取文件 目录下面子文件
        Iterable<SftpClient.DirEntry> iter = sftp.listDir(handle);
        Iterator<SftpClient.DirEntry> it = iter.iterator();
        while (it.hasNext()){
            SftpClient.DirEntry file = it.next();
            System.out.println("getFilename " + file.getFilename());
            System.out.println("getLongFilename " +  file.getLongFilename());

        }
        //读文件
        InputStream in = sftp.read("/var/2.txt");
        List<String> listStr = new ArrayList<>();
        List<String> content = IoUtil.readLines(in,"UTF-8",listStr);

        //写文件 会覆盖旧的文件
        FileInputStream in2 = new FileInputStream(localPath);
        OutputStream outputStream = sftp.write("/var/3.txt");
        outputStream.write(IoUtil.readBytes(in2));
        outputStream.close();
        in2.close();

        //删文件
        sftp.remove("/var/3.txt");


        sftp.close(handle);

        session.close(false);
        client.stop();
    }

    public static void main(String[] args) throws IOException {
        SFTPUtil.uploadSFTP("C:\\Users\\hh\\Desktop\\以店包片.txt","/var/2.txt");
        //SFTPUtil.readSFTP("C:\\Users\\hh\\Desktop\\以店包片.txt","/");
    }


}
